<?php
function string_template($string, $array=array()) {
	global $conf, $lang, $thm_img;

	$array['theme_values']='<pre>'.print_r($array, true).'</pre>';
	$index=array_keys($array);

	for($i=0;$i<count($index);$i++)
		$string=str_replace('{'.$index[$i].'}', $array[$index[$i]], $string);

	return($string);
}

function read_file($url) {
	#load from module themes dir
	if(file_exists($GLOBALS['theme_path'].$_GET['module'].'/'.$url))
		$url=$GLOBALS['theme_path'].$_GET['module'].'/'.$url;
	elseif(file_exists($GLOBALS['theme_path'].$url))
		$url=$GLOBALS['theme_path'].$url;
		
	$fp = @fopen ($url, 'r');

	if($fp) {
		while($read=fread($fp, 2048)) $string.=$read;
	}
	else
		$string='Theme error -> could not open file, (probably does not exist or you set wrong permission): <B>'.$url.'</B>';
	
	@fclose($fp);

	return ($string);
}

if(!function_exists('file_get_contents')) {
	function file_get_contents($url) {
		$fp=@fopen($url, 'r');
		if(!$fp) return false;
		$data='';
		while(!feof($fp)) $data.=fgets($fp, 1024);
		@fclose($fp);
		return $data;
	}
}

if(!function_exists('file_put_contents')) {
	function file_put_contents($url, $data) {
		$fp=@fopen($url, 'w');
		if(!$fp) return false;
		fwrite($fp, $data);
		@fclose($fp);
		return $data;
	}
}

//function change variables to html, addslashes
function changeGETPOST (){
	//dodawanie '/', zamiana znak�w na odpowiedniki html'a
	foreach($_GET as $key => $value) {
		if(!get_magic_quotes_gpc())
		    $_GET[$key] = addslashes($_GET[$key]);
		$_GET[$key] = htmlspecialchars($_GET[$key], ENT_NOQUOTES);
	}

	foreach($_POST as $key => $value) {
		if(!get_magic_quotes_gpc())
			$_POST[$key] = addslashes($_POST[$key]);
		if(!is_array($_POST[$key]))
			$_POST[$key] = htmlspecialchars($_POST[$key], ENT_NOQUOTES);
	}

	foreach($_REQUEST as $key => $value) {
		if(!get_magic_quotes_gpc())
			$_REQUEST[$key] = addslashes($_REQUEST[$key]);
		if(!is_array($_REQUEST[$key])) {
			$_REQUEST[$key] = htmlspecialchars($_REQUEST[$key], ENT_NOQUOTES);
			if(@ini_get('register_globals')==1) {
				if(in_array($key, array_keys($_SESSION)))
					$GLOBALS[$key]=$_SESSION[$key];
				elseif(in_array($key, array_keys($_COOKIE)))
					$GLOBALS[$key]=$_COOKIE[$key];
				else
					$GLOBALS[$key]=NULL;
			}
		}
	}
	
	foreach($_SERVER as $key => $value) {
		if(!is_array($_SERVER[$key]))
			$_SERVER[$key] = str_replace(array('<', '>', "'", '"'), array('&lt;', '&gt;', '&#039;', '&quot;'), $_SERVER[$key]);
		$_SERVER[$key] = addslashes($_SERVER[$key]);
	}
}

//changing theme
function change_theme() {
	global $conf;

	if($_POST['theme'])
	$_GET['theme'] = $_POST['theme'];

	if(file_exists('./themes/'.$_GET['theme'].'/gfx/images.php')) {
		if($_GET['theme']) {
			$_SESSION['theme'] = $_GET['theme'];

			if($_SESSION['logged_in'] == 1) {
				$db = new dbquery;
				$db->query("UPDATE $conf[prefix_users]users SET theme = '$_SESSION[theme]' WHERE login = '$_SESSION[login]'");
			}
		}
	}
	redirect($_SERVER['HTTP_REFERER']);
}
//

//funkcja wyswietlajaca w menu list�dostepnych them� - uzycie (w menu napisz [php]=theme();[/php])
function theme() {
	$theme_options='';
	//generating list of themes
	if ($dir = opendir("themes")) {
		while($file = readdir($dir)) {
			if($file==$_SESSION['theme'])
			$checked='selected="true"';
			else
			$checked='';
			$file_=add_dots_($file, 8);
			if(($file != ".") && ($file != ".."))
			$theme_options.='<option value="'.$file.'" '.$checked.'>'.$file_.'</option>';
		}
		closedir($dir);
	}
	//

	return '<form action="index.php" method="post"><table>
<tr>
     <td>
	 <select name="theme" class="button">'.$theme_options.'</select>
     </td>
</tr>
<tr>
     <td><input type="hidden" name="function" value="change_theme" /><input type="submit" value="'.$GLOBALS['lang']['global']['change'].'" class="button" /></td>
</tr>
</table></form>';
}
//

//zwracanie listy themow oddzielonych przecinkami
function get_theme_names() {
	$theme=array();
	if($dir=opendir('./themes')) {
		while($file = readdir($dir)) {
			if(($file != ".") && ($file != "..") && file_exists('./themes/'.$file.'/gfx/images.php'))
			$theme[]=$file;
		}
		closedir($dir);
	}
	return implode(', ', $theme);
}
//

//zwracanie listy themow formie tablicy
function get_theme_array() {
	$theme=array();
	if($dir=opendir('themes')) {
		while($file = readdir($dir)) {
			if(($file != ".") && ($file != "..") && file_exists('./themes/'.$file.'/gfx/images.php'))
			$theme[]=$file;
		}
		closedir($dir);
	}
	return $theme;
}
//

//dodanie funkcji do bazy
function function_install() {
	global $conf;

	if(perms_check('admin', 'modules')) {
		$db = new dbquery;
		if(file_exists("includes/functions/$_GET[variable].php")) {
			include_once("includes/functions/$_GET[variable].php");
			$f = $_GET['variable'].'_inst';
			if(function_exists($f))	$f();
			
			$db->query("INSERT INTO $conf[prefix]functions VALUES('$_GET[variable]', 1, '$GLOBALS[i_module]', '$GLOBALS[i_admin]', '$GLOBALS[i_function]')");
		}

		$db->clear_cache('groups_pdefs.cache', 'groups');
		$db->clear_cache('conf.cache', '');
		$db->clear_cache('*', 'menu');
		$db->clear_cache('functions.cache', '');
		$db->clear_cache('*', 'functions');
		$db->clear_cache('lang*', 'lang');
		$db->clear_cache('group*', 'groups');
	}

	redirect('index.php?module=admin&action=func');
	exit;
}
//

//usuniecie funkcji z bazy
function function_uninstall() {
	global $conf;

	if(perms_check('admin', 'modules') && can_uninstall($_GET['variable'])) {
		$db = new dbquery;
		$db->query("DELETE FROM $conf[prefix]functions WHERE name='$_GET[variable]'");
		include_once("includes/functions/$_GET[variable].php");
		$f = $_GET['variable'].'_uninst';
		if(function_exists($f)) $f();

		$db->clear_cache('groups_pdefs.cache', 'groups');
		$db->clear_cache('conf.cache', '');
		$db->clear_cache($_GET['variable'].'.cache', 'functions');
		$db->clear_cache('functions.cache', '');
		$db->clear_cache('*', 'functions');
		$db->clear_cache('lang*', 'lang');
		$db->clear_cache('group*', 'groups');
	}

	redirect('index.php?module=admin&action=func');
	exit;
}
//


//funckja sprawdzajaca czy podany modul jest zainstalowany
function is_module_installed($what) {
	global $conf;

	$db = new dbquery;
	$db->cache('modules_installed', 'functions');
	$db->query("SELECT * FROM $conf[prefix]functions WHERE 1");
	
	$return=false;
	while($d=$db->fetch_object()) {
		if($d->name==$what)
			$return=$d;
	}
	
	return $return;
}
//

//czy mozna odinstalowac dany modul
function can_uninstall($what) {
	global $conf;

	$db = new dbquery;
	$db->query("SELECT * FROM $conf[prefix]functions WHERE name='$what'");
	$f=$db->fetch_object();

	if($db->num_rows()==0)
		return false;
	
	if($f->uninstall==0)
		return false;
	else
		return true;
}
//

//adding conf value
function conf_field_add($name, $value, $cat, $help_en, $help_pl='', $type='text', $size='25', $maxlength='255') {
	global $conf;
	if(!$name) exit;
	
	if(!perms_check('admin', 'config')) {
		redirect('index.php?module=error&error=auth_error');
		exit;
	}
	
	if(!$cat)
		$cat='others';
	
	if(!$help_pl)
		$help_pl=$help_en;
	
	$db = new dbquery;
	$db->query("INSERT INTO `".$conf['prefix']."conf` VALUES('".$name."', '".addslashes($value)."', '".$size."', '".$maxlength."', '".$type."', '".addslashes($help_en)."', '".addslashes($help_pl)."', '".$cat."')") or $db->err(__FILE__, __LINE__);

	$db->clear_cache('conf.cache');
}

//adding conf value
function conf_field_delete($name='', $cat='') {
	global $conf;
	if(!$name && !$cat) exit;	
	
	if(!perms_check('admin', 'config')) {
		redirect('index.php?module=error&error=auth_error');
		exit;
	}
	
	if($name)
		$query="DELETE FROM `$conf[prefix]conf` WHERE `name`='".$name."'";
	elseif($cat)
		$query="DELETE FROM `$conf[prefix]conf` WHERE `cat`='".$cat."'";
	
	$db = new dbquery;
	$db->query($query);

	$db->clear_cache('conf.cache');
}

//edycja bazy configu
function conf_edit() {
	global $conf, $_GET;

	if(!perms_check('admin', 'config')) {
		redirect('index.php?module=error&error=auth_error');
		exit;
	}

	$thm=get_theme_array();

	if(!in_array($_POST['theme'], $thm)) {
		redirect('index.php?module=error&error=conf_error1');
		exit;
	}

	$l=get_lang_list();

	if(!in_array($_POST['language'], $l)) {
		redirect('index.php?module=error&error=conf_error2');
		exit;
	}

	$db = new dbquery;
	$db2 = new dbquery;

	$db->query("SELECT * FROM $conf[prefix]conf");

	while($d=$db->fetch_object()) {
		$value=read_text_html($_POST[$d->name]);
		if($d->value!=$value)
		$db2->query("UPDATE $conf[prefix]conf SET value='$value' WHERE name='$d->name'");
	}

	$db->clear_cache('conf.cache');

	redirect($_SESSION['redirect_1']);
	exit;
}
//

// aktualizacja zmiennych do przekierowywania
function redirect_update() {
	if(!$_SESSION['redirect_1']) {
		$_SESSION['redirect_1']=$_SERVER['REQUEST_URI'];
		$_SESSION['redirect_2']=$_SESSION['redirect_1'];
	}
	else {
		if($_GET['module']!='error' && $_GET['module']!='info') {
			if($_SESSION['redirect_1']!=$_SERVER['REQUEST_URI'])
			$_SESSION['redirect_2']=$_SESSION['redirect_1'];
			$_SESSION['redirect_1']=$_SERVER['REQUEST_URI'];
		}
	}
}
//

//redirect
function redirect ($page, $header=false) {
  
  $page=read_text_rest($page);
  
  if($header) {
	header($header);
	header("Location: ".$page); 
  }
  else {
	if($_SERVER['REQUEST_URI']==$page)
		$page='index.php';
	
	if($_POST['redirect'])
		$page=read_text_rest($_POST['redirect']);
	
	//echo('<meta http-equiv="refresh" content="0; url='.$page.'" />');
	header("Location: ".$page); 
  }
}
//

//funckja zwracaj�ca link do stron z podanych argument�w
function split_to_pages($template, $on_one, $all, $rec, $goto_=true) {
	$x=ceil($all/$on_one);
	$page=($rec/$on_one);

	$page_link='';
	if($x>5)
	{
		if($page>1 && $page!=($x-1))
		{
			if($page>1)
			$page_link.='... ';

			for($i=($page-1);$i<($page+2);$i++)
			{
				if($page==$i)
				$page_link.=string_template($template, array('rec' => ($i*$on_one), 'nr'=>'<b>'.($i+1).'</b>'));
				else
				$page_link.=string_template($template, array('rec' => ($i*$on_one), 'nr'=>($i+1)));

				if(($i+1)!=($page+2))
				$page_link.=' ';
				else
				$page_link.=' ';
			}

			if(($x-1)!=($page+1))
			$page_link.='... ';
		}
		else
		{
			for($i=0;$i<3;$i++)
			{
				if($page==$i)
				$page_link.=string_template($template, array('rec' => ($i*$on_one), 'nr'=>'<b>'.($i+1).'</b>'));
				else
				$page_link.=string_template($template, array('rec' => ($i*$on_one), 'nr'=>($i+1)));

				if(($i+1)!=3)
				$page_link.=' ';
				else
				$page_link.=' ';
			}

			$page_link.=' ... ';

			for($i=($x-2);$i<$x;$i++)
			{
				if($page==$i)
				$page_link.=string_template($template, array('rec' => ($i*$on_one), 'nr'=>'<b>'.($i+1).'</b>'));
				else
				$page_link.=string_template($template, array('rec' => ($i*$on_one), 'nr'=>($i+1)));

				if(($i+1)!=$x)
				$page_link.=' ';
				else
				$page_link.=' ';
			}
		}

		//$page_link.=' / <span class="btn">'.string_template($template, array('rec' => (($x-1)*$on_one), 'nr'=>($x))).'</span>';
	}
	else
	{
		for($i=0;$i<$x;$i++)
		{
			if($page==$i)
				$page_link.=string_template($template, array('rec' => ($i*$on_one), 'nr'=>'<b>'.($i+1).'</b>'));
			else
				$page_link.=string_template($template, array('rec' => ($i*$on_one), 'nr'=>($i+1)));

			if(($i+1)!=$x)
			$page_link.=' ';
			else
			$page_link.=' ';
		}
	}


	if($x>1) {
		if($goto_) {
			preg_match("#href=\"(.*)\"#isU", $template, $url);
			$url=$url[1];
			$pg=rand(1, 100)+$x;
			if ($page+2>$x) $s=$x; else $s=$page+2;
			$goto=' : <input type="text" id="split_to_pages_'.$pg.'" class="button"  maxlength="5" size="1" value="'.$s.'" /> <input onclick="javascript: var str=\''.overlib_text($url).'\'; document.location=str.replace(\'{rec}\', \'\'+'.$on_one.'*(document.getElementById(\'split_to_pages_'.$pg.'\').value-1)+\'\');" type="button" class="button" value="'.$GLOBALS['lang']['global']['go'].'" /> ';
			
			$page_link.=$goto;	
		}	

		$prev=($page-1)*$on_one;
		$next=($page+1)*$on_one;
		
		if($rec>0)
			$page_link=string_template($template, array('rec' => '0', 'nr'=>'&lt;&lt;')).' '.string_template($template, array('rec' => $prev, 'nr'=>'&lt;')).' '.$page_link;
		if($rec!=$on_one*($x-1))
			$page_link.=string_template($template, array('rec' => $next, 'nr'=>'&gt;')).' '.string_template($template, array('rec' => (($x-1)*$on_one), 'nr'=>'&gt;&gt;'));
	}
	else
	$page_link='';

	return $page_link;
}

//funkcja do zmiany sortowania
function set_default_sort_order() {
	if(is_module_installed($_GET['what']) && in_array($_POST['sortby'], array('date', 'downloaded', 'rating', 'views', 'name', 'viewed', 'title_'.$_SESSION['lang_short']))){
		$_SESSION[$_GET['what'].'_sortby'] = $_POST['sortby'];

		if(in_array($_POST['sort'], array('ASC', 'DESC')))
		$_SESSION[$_GET['what'].'_sort'] = $_POST['sort'];	
	}
	
	redirect($_SESSION['redirect_1']);
	exit;
}

//deleting SQL or tpl cache
function delete_cache (){
	if(perms_check('admin', 'cache')) {
		if($_GET['what']=='tpl'){ 
			$tpl=new tpl;
			$tpl->clear_cache('*', true);
		}
		if($_GET['what']=='sql'){
			$db=new dbquery;
			$db->clear_cache('*', '', true);
			$db->clear_cache('*', 'categories', true);
			$db->clear_cache('*', 'groups', true);
			$db->clear_cache('*', 'lang', true);
			$db->clear_cache('*', 'menu', true);
			$db->clear_cache('*', 'ranks', true);
			$db->clear_cache('*', 'functions', true);
			plugins('std/sql_cache/');
		}
	}

	redirect($_SESSION['redirect_1']);
	exit;
}

function glob_($pattern) {
	$output=$path=NULL;
	$slash='/';

	$exp=explode($slash, $pattern);
	for($i=0;$i<count($exp)-1;$i++)
	$path.=$exp[$i].'/';

	$pattern=str_replace($path, '', $pattern);

	$handle=opendir($path);
	if($handle===false)
	return array();
	while($dir=readdir($handle)) {
		if(pattern_match($pattern, $dir))
		$output[]=$path.$dir;
	}
	closedir($handle);

	if(is_array($output))
	return $output;

	return array();
}

//function to manage plugins
function plugins ($dir, $return=false, $w='plugins/') {
	if(!$dir) exit;
	
	$path=$w.$dir;
	$value='';
	
	//if(strpos($path, '../')!==false) exit; 
	
	//if we want to return echo'ed plugin watch the output
	//if($return) ob_start();

	$handle=opendir($path);
	if(!$return) {
		while($file=readdir($handle))
			if(!is_dir($path.$file) && end($foo=explode('.', $file))=='php') include($path.$file);
	} else {
		while($file=readdir($handle))	if(!is_dir($path.$file) && end($foo=explode('.' ,$file))=='php')	$value.=read_file($path.$file);
	}
	closedir($handle);
	
	//return watched output
	//if($return) return ob_get_clean();
	if($return) return $value;
}
//

//function used in glob_ function
function pattern_match($pattern, $string) {
	$out=null;
	$chunks=explode(';',$pattern);

	foreach($chunks as $pattern) {
		$escape=array('$','^','.','{','}', '(',')','[',']','|');

		while(strpos($pattern,'**')!==false)
		$pattern=str_replace('**','*',$pattern);

		foreach($escape as $probe)
		$pattern=str_replace($probe,"\\$probe",$pattern);

		$pattern=str_replace('?*','*', str_replace('*?','*', str_replace('*',".*", str_replace('?','.{1,1}',$pattern))));
		$out[]=$pattern;
	}
	if(count($out)==1)
	return(eregi("^$out[0]$",$string));
	else {
		foreach($out as $tester)
		if(eregi("^$tester$",$string))
		return true;
		return false;
	}
}

function filesize_remote($url, $timeout=2) {
	$url = parse_url($url);
	  
	if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
	    fwrite($fp, 'HEAD '.$url['path'].$url['query']." HTTP/1.0\r\nHost: ".$url['host']."\r\n\r\n");
		stream_set_timeout($fp, $timeout);
	       
		while (!feof($fp)) {
			$size = fgets($fp, 4096);
			if (stristr($size, 'Content-Length') !== false) {
				$size = trim(substr($size, 16));
				break;
			}
	   }
	   fclose ($fp);
	}
	return is_numeric($size) ? intval($size) : false;
}

//verifing e-mail address
function verify_mail($email) {
	$email= urldecode($email);
	if (strpos($email, "\r")!==false || strpos($email, "\n"))
		return false;
  
	$wholeexp = '/^(.+?)@(([a-z0-9\.-]+?)\.[a-z]{2,5})$/i';
	$userexp = "/^[a-z0-9\~\!\#\$\%\&amp;\(\)\-\_\+\=\[\]\;\:\'\"\,\.\/]+$/i";
	if (preg_match($wholeexp, $email, $regs)) {
		$username = $regs[1];
		$host = $regs[2];
		if (preg_match($userexp, $username))
		return true;
		else
		return false;
	}
	else
	return false;
}

function SQLvalidate( $value, $type = 'int', $max_width = 0 ) {
	$max_sizes = array (
	'int'		=>	10,
	'tinyint'	=>	3,
	'smallint'	=>	5,
	'mediumint'	=>	7,
	'varchar'	=>	255,
	'text'		=>	65535,
	'mediumtext'	=>	16777215,
	'char'		=>	255,
	'date'		=>	10,
	'datetime'	=>	20,
	'timestamp'	=>	20,
	'time'		=>	9
	);

	$ok = 1;

	switch($type) {
		case 'tinyint':
		case 'smallint':
		case 'int':
			if(!is_numeric($value) or strpos($value, '.') !== false)
			$ok = 0;
			break;
		case 'date':
			if(!ereg("^(19|20)[0-9]{2}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$", $value))
			$ok = 0;
			break;
		case 'datetime':
		case 'timestamp':
			if(!ereg("^(19|20)[0-9]{2}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]) [0-9]{2}(:[0-9]{2})?(:[0-9]{2})?$", $value))
			$ok = 0;
			break;
		case 'time':
			if(!ereg("^[0-9]{2}(:[0-9]{2})?(:[0-9]{2})?$", $value))
			$ok = 0;
			break;
	}

	if(max($max_sizes[$type], $max_width) < strlen($value))
	$ok = 0;

	if(!$value)
	$ok = 1;

	if($ok == 0) {
		require_once("includes/functions/logs.php");
		plugins('std/unauth/');
		redirect('index.php?module=error&error=form_error');
		exit;
	}
	else
	return true;
}

function check_install() {
	if((file_exists('install/') or file_exists('install.php')) && file_exists('includes/conf.php')) {
		redirect('install.php');
	} else {
		redirect('index.php');
	}
}

//funcja do pobierania kodu
function get_code(){
	global $conf;
	
	header('Content-Type: text/html; charset='.$conf['html_character_set']);

	header();
	if(strpos($_SERVER['HTTP_REFERER'], str_replace(array('http://', 'www.'), array('', ''),$conf['adres']))!==false or !$_SERVER['HTTP_REFERER'])
		echo(passgen());
	else
		echo($_SERVER['HTTP_REFERER'].'<br />'.$conf['adres']);
}


//funcja do sprawdzania czy wpis by� dokonany przez bota czy nie
function checkCode($code){
   if(img_pwd_validate($code)) return true;
   else exit('Wrong anti-bot code');
}

?>
